import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:zhaoxiaowu_app/global/global.dart';
import 'package:zhaoxiaowu_app/models/accounting.dart';
import 'package:zhaoxiaowu_app/models/accounting_info.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';

class AccountingViewModel extends ChangeNotifier {
  Accounting _model = Accounting();
  int _month = 0;

  int get itemCount => dataList.length;

  List<AccountingInfo> get dataList => _model.data ?? [];

  void setModel(Accounting newValue) {
    _model = newValue;
    notifyListeners();
  }

  int get month {
    if (_month == 0) return DateTime.now().month;
    return _month;
  }

  void setMonth(int newValue) {
    _month = newValue;
    notifyListeners();
  }

  double get income => _model.income ?? 0.0;

  double get expenditure => _model.expenditure ?? 0.0;

  void getAccountingHistory() async {
    ToastUtils.showActivity();

    var result = await Global.shared().get(
      "/zxw/AccountingHistory",
      parameters: {
        "date": DateTime.now().year.toString() + (month < 10 ? "0$month" : "$month"),
      },
    );

    print("记账: ${result.toString()}");

    var data = result.data;

    if (data["success"]) {
      Accounting model = Accounting.fromJson(data["data"]);
      setModel(model);
    } else {
      ToastUtils.showError(result.data["msg"]);
    }
  }

  void delete(String id) async {
    Response result = await Global.shared().delete(
      "/zxw/AccountingHistory",
      parameters: {"id": id},
    );

    if (result.data["success"]) {
      getAccountingHistory();
    } else {
      ToastUtils.showError(result.data["msg"]);
    }
  }
}
